package com.dime.physical.service.impl;

import com.alibaba.fastjson.JSON;
import com.dime.basic.api.RemoteBaseCombService;
import com.dime.basic.api.domain.DimeBasecomb;
import com.dime.basic.api.domain.DimeBaseharm;
import com.dime.basic.api.domain.DimeBaseitem;
import com.dime.basic.api.model.Combo;
import com.dime.basic.api.model.ComboBase;
import com.dime.basic.api.model.Item;
import com.dime.mninterface.api.RemoteHealth100Service;
import com.dime.mninterface.api.model.Package;
import com.dime.mninterface.api.model.*;
import com.dime.physical.service.IDimeInquiryService;
import com.ruoyi.common.core.utils.file.MyMultipartFile;
import com.dime.physical.domain.*;
import com.dime.physical.domain.dto.*;
import com.dime.physical.mapper.*;
import com.dime.physical.service.IDimeBasepackageService;
import com.dime.physical.service.IDimePhysicalflowService;
import com.dime.physical.service.IDimePhysicalregisterService;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.file.ImageUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.RemoteLogService;
import com.ruoyi.system.api.domain.SysFile;
import com.ruoyi.system.api.domain.SysOperLog;
import org.apache.http.entity.ContentType;
import org.apache.poi.util.SystemOutLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.rmi.runtime.Log;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 人员登记Service业务层处理
 *
 * @author Tiny
 * @date 2023-09-14
 */
@Service
public class DimePhysicalregisterServiceImpl implements IDimePhysicalregisterService {
    @Autowired
    private DimePhysicalregisterMapper dimePhysicalregisterMapper;

    @Autowired
    private DimePhysicalflowMapper dimePhysicalflowMapper;

    @Autowired
    private DimePhysicalharmsMapper dimePhysicalharmsMapper;

    @Autowired
    private RemoteHealth100Service remoteHealth_100Service;

    @Autowired
    private DimeBasecompanyMapper dimeBasecompanyMapper;


    @Autowired
    private DimePhysicalcombsMapper dimePhysicalcombsMapper;

    @Autowired
    private DimePhysicalheadpicMapper dimePhysicalheadpicMapper;

    @Autowired
    private RemoteBaseCombService remoteBaseCombService;

    @Autowired
    private DimePhysicalitemsMapper dimePhysicalitemsMapper;

    @Autowired
    private DimePhysicaladviceMapper dimePhysicaladviceMapper;

    @Autowired
    private DimePhysicalconsionMapper dimePhysicalconsionMapper;

    @Autowired
    private DimePhysicalpictureMapper dimePhysicalpictureMapper;


    @Autowired
    private IDimeBasepackageService dimeBasepackageService;

    @Autowired
    private IDimePhysicalflowService dimePhysiacaflowService;

    @Autowired
    private RemoteFileService remoteFileService;

    @Lazy
    @Autowired
    private IDimeInquiryService dimeInquiryService;



    /**
     * 查询人员登记
     *
     * @param id 人员登记主键
     * @return 人员登记
     */
    @Override
    public DimePhysicalregister selectDimePhysicalregisterById(String id) {

        return dimePhysicalregisterMapper.selectDimePhysicalregisterById(id);
    }

    /**
     * 查询人员登记列表
     *
     * @param dimePhysicalregister 人员登记
     * @return 人员登记
     */
    @Override
    public List<DimePhysicalregister> selectDimePhysicalregisterList(DimePhysicalregister dimePhysicalregister) {


        return dimePhysicalregisterMapper.selectDimePhysicalregisterList(dimePhysicalregister);
    }

    /**
     * 新增人员登记
     *
     * @param dimePhysicalregister 人员登记
     * @return 结果
     */
    @Override
    public int insertDimePhysicalregister(DimePhysicalregister dimePhysicalregister) {

        dimePhysicalregister.setCreateTime(DateUtils.getNowDate());
        return dimePhysicalregisterMapper.insertDimePhysicalregister(dimePhysicalregister);
    }

    /**
     * 修改人员登记
     *
     * @param dimePhysicalregister 人员登记
     * @return 结果
     */
    @Override
    public int updateDimePhysicalregister(DimePhysicalregister dimePhysicalregister) {
        dimePhysicalregister.setUpdateTime(DateUtils.getNowDate());
        return dimePhysicalregisterMapper.updateDimePhysicalregister(dimePhysicalregister);
    }

    /**
     * 批量删除人员登记
     *
     * @param ids 需要删除的人员登记主键
     * @return 结果
     */
    @Override
    public int deleteDimePhysicalregisterByIds(String[] ids) {
        //return dimePhysicalregisterMapper.deleteDimePhysicalregisterByIds(ids);


        return  dimePhysicalregisterMapper.softdeleteDimePhysicalregisterByIds(ids);
    }

    /**
     * 删除人员登记信息
     *
     * @param dimePhysicalregister 人员登记主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteDimePhysicalregisterById(DimePhysicalregister dimePhysicalregister) {
        int rows = 0;

        String id = dimePhysicalregister.getId();
        //问诊
        rows += dimeInquiryService.Revokeinquiry(dimePhysicalregister);
        rows += dimePhysicalitemsMapper.deleteDimePhysicalitemsByPhysicalId(id);
        rows += dimePhysicalflowMapper.deleteDimePhysiacaflowByPhysicalId(id);
        rows += dimePhysicalharmsMapper.deleteDimePhysicalharmsByPhysicalId(id);
        rows += dimePhysicaladviceMapper.deleteDimePhysicaladviceByPhysicalId(id);
        rows += dimePhysicalcombsMapper.deleteDimePhysicalcombsByPhysicalId(id);
        rows += dimePhysicalconsionMapper.deleteDimePhysicalconsionByPhysicalId(id);
        rows += dimePhysicalheadpicMapper.deleteDimePhysicalheadpicByPhysicalId(id);
        rows += dimePhysicalpictureMapper.deleteDimePhysicalpictureByPhysicalId(id);
        rows += dimePhysicalregisterMapper.deleteDimePhysicalregisterById(id);

        return rows;
    }


    @Override
    public List<PhysicalDto> getBQregisterInfoByidnoOrvid(String idno,String vid) {

        String shopCode = SecurityUtils.getShopId();
        RegistRequestBody requestBody = new RegistRequestBody();
        requestBody.setBranchCode(shopCode);
        if (!Objects.equals(idno, "")) {
            requestBody.setCertificateNumber(idno);
        } else if (!Objects.equals(vid, "")) {
            requestBody.setVid(vid);
        }

        MNResponse<List<MNRegist>> serviceRegists = remoteHealth_100Service.getRegist(requestBody);

        List<PhysicalDto> physicalDtos = new ArrayList<>();

        if (Objects.equals(serviceRegists.getCode(), "000000") && serviceRegists.getData() != null) {


            for (MNRegist register : serviceRegists.getData()) {

                PhysicalDto physicalDto = new PhysicalDto();
                physicalDto.setShopCode(shopCode);
                physicalDto.physicalCombDtos = new ArrayList<>();


                //获取对应单位信息
                DimeBasecompany basecompany = dimeBasecompanyMapper.selectDimeBasecompanyByCode(register.getCompanyCode());
                if (basecompany != null) {
                    physicalDto.setBaseCompanyId(basecompany.getId());
                    physicalDto.setCompanyName(basecompany.getCompanyName());
                    physicalDto.setBasecompany(basecompany);
                } else {
                    throw new ServiceException(register.getBranchName() + ">未同步套餐基础信息");
                }


                //获取套餐信息
                List<Package> packageList = register.getPackages();

                if (packageList != null) {

                    for (Package _package : packageList) {

                        if (Objects.equals(_package.getPackageType(), "PACKAGE")) {

                            DimeBasepackage basePackage = dimeBasepackageService.selectDimeBasepackageByCode(_package.getPackageCode());//dimeBasepackageMapper.selectDimeBasepackageByCode(_package.getPackageCode());
                            if (basePackage != null) {
                                physicalDto.setBasePackageId(basePackage.getId());
                                physicalDto.setPackageName(basePackage.getPackageName());
                                physicalDto.setBasepackage(basePackage);

                                //套餐对应的 危害 体检类型
                                if (basePackage.dimeBaseharmList != null && basePackage.dimeBaseharmList.size() > 0) {
                                    physicalDto.dimeBaseharmList = basePackage.dimeBaseharmList;
                                } else {
                                    physicalDto.dimeBaseharmList = new ArrayList<>();
                                }

                                if (basePackage.getWorktype() != null) {
                                    physicalDto.setCheckType(basePackage.getWorktype());
                                }
                                if (basePackage.getTouchHarms() != null) {
                                    physicalDto.setTouchHarms(basePackage.getTouchHarms());
                                }
                            } else if (!Objects.equals(register.getCheckupType(), "REPEAT")) {
                                throw new ServiceException(_package.getPackageName() + ">未同步套餐基础信息");
                            }

                        }

                        List<ComboBase> basecombs = _package.getItems().stream().map(x -> {
                            ComboBase basecomb = new ComboBase();
                            basecomb.setCombCode(x.getItemCode());
                            basecomb.setCombName(x.getItemName());
                            return basecomb;
                        }).collect(Collectors.toList());

//                        R<DimeBasicDataResult> combs = remoteBaseCombService.checkCombos(basecombs, SecurityConstants.INNER);
//                        if (combs.getCode() == R.FAIL) {
//                            List<ComboBase> _combs = combs.getData() == null ? null : (List<ComboBase>) combs.getData();
//                            if (_combs != null)
//                                throw new ServiceException(String.join((CharSequence) ",", (CharSequence) _combs.stream().map(ComboBase::getCombName)) + ">未维护基础项目信息！");
//                        }

                        List<String> CombCodes = basecombs.stream().map(ComboBase::getCombCode).collect(Collectors.toList());
                        String Codes = String.join(",", CombCodes);

                        R<List<ComboBase>> RcombList = remoteBaseCombService.getCombosByCodes(Codes, SecurityConstants.INNER);

                        if (RcombList.getCode() != R.FAIL && RcombList.getData() != null) {

                            List<ComboBase> comboBaseList = RcombList.getData();

                            //遍历package中items
                            for (ComboBase _combbase : comboBaseList) {

                                PhysicalCombDto combDto = new PhysicalCombDto();
                                combDto.setCombCode(_combbase.getCombCode());
                                combDto.setCombName(_combbase.getCombName());
                                combDto.setId(_combbase.getId());
                                combDto.setDimeGroupsid(_combbase.getGroupid());
                                combDto.setGroupName(_combbase.getGroupName());
                                combDto.setCombType(_combbase.getCombType());

                                List<Item> items = _combbase.getItems();
                                if (_combbase.getItems() != null) {
                                    combDto.items = new ArrayList<>();
                                    for (Item items1 : items) {
                                        PhysicalItemsDto itemsDto = new PhysicalItemsDto();
                                        itemsDto.setId(items1.getId());
                                        itemsDto.setItemCode(items1.getItemCode());
                                        itemsDto.setItemName(items1.getItemName());
                                        itemsDto.setItemType(items1.getItemType());
                                        itemsDto.setUnit(items1.getUnit());
                                        itemsDto.setJudgeType(items1.getJudgeType());
                                        itemsDto.setValDefault(items1.getValDefault());
                                        itemsDto.setValmax(items1.getValmax());
                                        itemsDto.setValmin(items1.getValmin());
                                        itemsDto.setHistr(items1.getHistr());
                                        itemsDto.setLwstr(items1.getLwstr());
                                        itemsDto.setSn(items1.getSn());
                                        itemsDto.setValStandard(items1.getValStandard());
                                        itemsDto.setGroupName(_combbase.getGroupName());
                                        itemsDto.setGroupId(_combbase.getGroupid());
                                        combDto.items.add(itemsDto);
                                    }

                                }
                                physicalDto.physicalCombDtos.add(combDto);
                            }
                        }
                    }
                }

                //先判断是否为复查
                if (Objects.equals(register.getCheckupType(), "REPEAT")) {

                    // 复查  获取复查信息
                    DimePhysicalregister searchphysical = new DimePhysicalregister();
                    searchphysical.setIdNo(register.getCustomer().getCertificateNumber());
                    searchphysical.setRegistertype("INITIAL");
                    searchphysical.setServiceUid(register.getServiceUid());

                    DimePhysicalregister recheckphysical = dimePhysicalregisterMapper.selectDimePhysicalregisterList(searchphysical).stream().findFirst().orElse(null);
                    if (recheckphysical != null) {

                        physicalDto.setCheckType(recheckphysical.getCheckType());
                        physicalDto.setTouchHarms(recheckphysical.getTouchHarms());
                        physicalDto.setWorkStatus(recheckphysical.getWorkStatus());

                        List<DimePhysicalharms> dimePhysicalharms = dimePhysicalharmsMapper.selectDimePhysicalharmsByPhysicalId(recheckphysical.getId());

                        List<DimeBaseharm> dimeBaseharms = new ArrayList<>();
                        if (dimePhysicalharms != null && dimePhysicalharms.size() > 0) {

                            for (DimePhysicalharms dimePhysicalharms1 : dimePhysicalharms) {
                                DimeBaseharm dimeBaseharm = new DimeBaseharm();
                                dimeBaseharm.setId(dimePhysicalharms1.getBaseHarmId());
                                dimeBaseharm.setHamName(dimePhysicalharms1.getBaseHarmName());
                                dimeBaseharms.add(dimeBaseharm);
                            }
                        }
                        physicalDto.dimeBaseharmList = dimeBaseharms;

                        physicalDto.setWorkMonths(recheckphysical.getWorkMonths() == null ? 0L : recheckphysical.getWorkMonths());
                        physicalDto.setWorkYears(recheckphysical.getWorkYears() == null ? 0L : recheckphysical.getWorkYears());
                        physicalDto.setTouchMonths(recheckphysical.getTouchMonths() == null ? 0L : recheckphysical.getTouchMonths());
                        physicalDto.setTouchYears(recheckphysical.getTouchYears() == null ? 0L : recheckphysical.getTouchYears());


                    } else {
                        throw new ServiceException(register.getCustomer().getCustomerName() + "未匹配到登记的初检人员信息！");
                    }
                } else {
                    physicalDto.setWorkMonths(Long.parseLong(register.getTotalWorkingMonths() == null ? "0" : register.getTotalWorkingMonths()));
                    physicalDto.setWorkYears(Long.parseLong(register.getTotalWorkingYears() == null ? "0" : register.getTotalWorkingYears()));
                    physicalDto.setTouchMonths(Long.parseLong(register.getWorkInHazardousPositionsMonths() == null ? "0" : register.getWorkInHazardousPositionsMonths()));
                    physicalDto.setTouchYears(Long.parseLong(register.getWorkInHazardousPositionsYears() == null ? "0" : register.getWorkInHazardousPositionsYears()));

                }

                physicalDto.setAge(register.getCustomer().getAge());
                physicalDto.setIdNoType(register.getCustomer().getCertificateType());
                physicalDto.setIdNo(register.getCustomer().getCertificateNumber());
                physicalDto.setSex(register.getCustomer().getGender());
                physicalDto.setPhone(register.getCustomer().getPhone());
                physicalDto.setName(register.getCustomer().getCustomerName());
                physicalDto.setMarriage(register.getCustomer().getMaritalStatus());
                physicalDto.setHeadUrl(register.getCustomer().getPicUrl());
                physicalDto.setCheckCode(register.getVid());
                physicalDto.setServiceUid(register.getServiceUid());
                physicalDto.setCheckType("02");
                physicalDto.setCompletStatus("0");
                physicalDto.setSoaOrderNo(register.getSoaOrderNo());
                physicalDto.setRegisterDate(DateUtils.parseDate(register.getCheckinTime()));
                physicalDto.setAddress(register.getAddress());
                physicalDto.setNationality(register.getNationalityName());
                physicalDto.setNation(register.getNationName());
                physicalDto.setAddress(register.getAddress());
                physicalDto.setRegistertype(register.getCheckupType());

                if (register.getDept() != null && register.getDept().split("-").length > 1) {
                    physicalDto.setDept(register.getDept().split("-")[0]);
                    physicalDto.setJobType(register.getDept().split("-")[1]);
                }

                physicalDtos.add(physicalDto);
            }

            return physicalDtos;
        }

        throw new ServiceException("未查询到人员信息！");
    }



    @Override
    public DimePhysicalregister checkregisterInfoByVid(String vid) {

        DimePhysicalregister physicalregister = dimePhysicalregisterMapper.selectDimePhysicalregisterByVid(vid);
        return physicalregister;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBQregister(PhysicalDto physicalDto) {

        DimePhysicalregister physicalregister = new DimePhysicalregister();

        physicalregister = physicalDto;
        physicalregister.setCreateTime(DateUtils.getNowDate());
        physicalregister.setId(IdUtils.fastUUID());
        physicalregister.setCreateBy(SecurityUtils.getUsername());

        List<PhysicalCombDto> physicalCombDtos = physicalDto.physicalCombDtos;



        //是否包含问诊项目
        if (physicalCombDtos.stream().anyMatch(x -> x.getCombType()!=null&&x.getCombType().contains("05"))) {
            physicalregister.setNeedAsk("1");
        }

        //是否复查

        if(Objects.equals(physicalregister.getRegistertype(), "REPEAT")) {
            physicalregister.setReCheckTag("1");
        }



        //主表
        int rows = dimePhysicalregisterMapper.insertDimePhysicalregister(physicalregister);

        //流程表
        InsertCheckFlow(physicalCombDtos, physicalregister);
        //项目
        InsterCombs(physicalCombDtos, physicalregister);
        //item
        InsterItems(physicalCombDtos, physicalregister);
        //图片
        InsterheadPic(physicalDto);
        //危害
        if (physicalDto.dimeBaseharmList != null && physicalDto.dimeBaseharmList.size() > 0) {
            InsterCheckHarms(physicalDto.dimeBaseharmList, physicalregister);
        }

        return rows;
    }

    private void InsterItems(List<PhysicalCombDto> physicalCombDtos, DimePhysicalregister physicalregister) {
        for (PhysicalCombDto physicalCombDto : physicalCombDtos) {


            if (physicalCombDto.getItems() != null && physicalCombDto.getItems().size() > 0) {

                //循环保存 items
                for (DimeBaseitem physicalItemDto : physicalCombDto.getItems()) {


                    DimePhysicalitems physicalitem = new DimePhysicalitems();
                    physicalitem.setPhysicalRegisterId(physicalregister.getId());
                    physicalitem.setBaseGroupId(physicalCombDto.getDimeGroupsid());
                    physicalitem.setGroupName(physicalCombDto.getGroupName());
                    physicalitem.setBaseCombId(physicalCombDto.getId());
                    physicalitem.setCombCode(physicalCombDto.getCombCode());
                    physicalitem.setCombName(physicalCombDto.getCombName());
                    physicalitem.setBaseItemId(physicalItemDto.getId());
                    physicalitem.setItemCode(physicalItemDto.getItemCode());
                    physicalitem.setItemName(physicalItemDto.getItemName());
                    physicalitem.setValDefault(physicalItemDto.getValDefault());
                    physicalitem.setValmax(physicalItemDto.getValmax());
                    physicalitem.setValmin(physicalItemDto.getValmin());
                    physicalitem.setUnit(physicalItemDto.getUnit());
                    physicalitem.setSn(physicalItemDto.getSn());
                    physicalitem.setId(IdUtils.fastUUID());
                    physicalitem.setCreateBy(SecurityUtils.getUsername());
                    physicalitem.setCreateTime(DateUtils.getNowDate());
                    physicalitem.setValStandard(physicalItemDto.getValStandard());
                    physicalitem.setSn(physicalItemDto.getSn());
                    physicalitem.setHistr(physicalItemDto.getHistr());
                    physicalitem.setLwstr(physicalItemDto.getLwstr());
                    physicalitem.setItemType(physicalItemDto.getItemType());


                    dimePhysicalitemsMapper.insertDimePhysicalitems(physicalitem);

                }

            }

        }
    }


    private void InsertCheckFlow(List<PhysicalCombDto> physicalCombDtos, DimePhysicalregister physicalregister) {

        List<String> groups = physicalCombDtos.stream().map(DimeBasecomb::getDimeGroupsid).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        for (String groupid : groups) {
            //判断 groupid不为空和null
            if (groupid != null && !"".equals(groupid)) {

                DimePhysicalflow physiacaflow = new DimePhysicalflow();
                PhysicalCombDto combDto = physicalCombDtos.stream().filter(x -> x.getDimeGroupsid().equals(groupid)).findFirst().orElse(null);
                if (combDto != null) {
                    physiacaflow.setGroupName(combDto.getGroupName());
                    physiacaflow.setType(combDto.getCombType());
                }

                physiacaflow.setCreateTime(DateUtils.getNowDate());
                physiacaflow.setId(IdUtils.fastUUID());
                physiacaflow.setCreateBy(SecurityUtils.getUsername());
                physiacaflow.setBaseGroupId(groupid);

                physiacaflow.setFlowStatus(0L);
                physiacaflow.setPhysicalRegisterId(physicalregister.getId());


                dimePhysicalflowMapper.insertDimePhysicalflow(physiacaflow);
            }
        }
    }

    private void InsterCheckHarms(List<DimeBaseharm> dimeBaseharmList, DimePhysicalregister physicalregister) {
        for (DimeBaseharm physicalharm : dimeBaseharmList) {

            DimePhysicalharms dimePhysicalharm = new DimePhysicalharms();
            dimePhysicalharm.setCreateTime(DateUtils.getNowDate());
            dimePhysicalharm.setId(IdUtils.fastUUID());
            dimePhysicalharm.setCreateBy(SecurityUtils.getUsername());
            dimePhysicalharm.setPhysicalRegisterId(physicalregister.getId());
            dimePhysicalharm.setBaseHarmId(physicalharm.getId());
            dimePhysicalharm.setBaseHarmName(physicalharm.getHamName());
            dimePhysicalharm.setBaseHarmcode(physicalharm.getHamrCode());
            dimePhysicalharmsMapper.insertDimePhysicalharms(dimePhysicalharm);
        }

    }


    private void InsterCombs(List<PhysicalCombDto> physicalCombDtos, DimePhysicalregister physicalregister) {
        //循环保存
        for (PhysicalCombDto physicalCombDto : physicalCombDtos) {
            DimePhysicalcombs dimePhysicalcomb = new DimePhysicalcombs();
            dimePhysicalcomb.setCreateTime(DateUtils.getNowDate());
            dimePhysicalcomb.setId(IdUtils.fastUUID());
            dimePhysicalcomb.setCreateBy(SecurityUtils.getUsername());
            dimePhysicalcomb.setPhysicalRegisterId(physicalregister.getId());
            dimePhysicalcomb.setBaseCombId(physicalCombDto.getId());
            dimePhysicalcomb.setBaseCombName(physicalCombDto.getCombName());
            dimePhysicalcomb.setBaseCombcode(physicalCombDto.getCombCode());

            dimePhysicalcombsMapper.insertDimePhysicalcombs(dimePhysicalcomb);
        }
    }

    private void InsterheadPic(PhysicalDto physicalDto) {
        //保存图片
        if (physicalDto.getHeadUrl() != null) {
            DimePhysicalheadpic dimePhysicalheadpic = new DimePhysicalheadpic();
            dimePhysicalheadpic.setCreateTime(DateUtils.getNowDate());
            dimePhysicalheadpic.setId(IdUtils.fastUUID());
            dimePhysicalheadpic.setCreateBy(SecurityUtils.getUsername());
            dimePhysicalheadpic.setPhysicalRegisterId(physicalDto.getId());
            dimePhysicalheadpic.setPicturtetype("0");
            //网络图片地址 HeadUrl 转 二进制

            byte[] imagesource=ImageUtils.readFile(physicalDto.getHeadUrl());
            dimePhysicalheadpic.setImagesoure(imagesource);

            dimePhysicalheadpicMapper.insertDimePhysicalheadpic(dimePhysicalheadpic);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int getReport(DimePhysicalregister physicalregister) {

        String shopCode = SecurityUtils.getShopId();
        ReportRequestBody requestBody = new ReportRequestBody();
        requestBody.setBranchCode(shopCode);
        requestBody.setServiceUid(physicalregister.getServiceUid());
        // ObjectMapper objectMapper = new ObjectMapper();
        MNResponse<MNReport> report = remoteHealth_100Service.getReport(requestBody);
        String json = JSON.toJSONString(report);
        System.out.print(json);
        if (Objects.equals(report.getCode(), "000000")) {
            FrontPage frontPage = report.getData().getFrontPage();
            physicalregister.setCheckDate(DateUtils.parseDate(frontPage.getExamDate()));

            MainCheckup mainCheckup = report.getData().getMainCheckup();

            //建议和医学解释
            List<MainAbnormal> mainAbnormals = mainCheckup.getMainAbnormalList();
            List<MainAbnormal> normalAbnormals = mainCheckup.getNormalAbnormalList();
            if (normalAbnormals != null) {
                mainAbnormals.addAll(normalAbnormals);
            }

            List<MedicalScience> medicalSciences = report.getData().getMedicalScienceList();
            if (mainAbnormals != null) {

                //清除 physicaladvice 重新保存

                dimePhysicaladviceMapper.deleteDimePhysicaladviceByPhysicalId(physicalregister.getId());

                for (MainAbnormal abnormal : mainAbnormals) {
                    DimePhysicaladvice physicaladvice = new DimePhysicaladvice();

                    physicaladvice.setId(IdUtils.fastUUID());
                    physicaladvice.setPhysicalRegisterId(physicalregister.getId());
                    physicaladvice.setCreateTime(DateUtils.getNowDate());
                    physicaladvice.setCreateBy(SecurityUtils.getLoginUser().getUsername());


                    if (abnormal.getAbnormalName() == null) {

                        List<MedicalScience> temp = new ArrayList<>();
                        for (MedicalScience medicalScience : medicalSciences) {
                            if (abnormal.getCheckResult().toString().contains(medicalScience.getTitle())) {
                                temp.add(medicalScience);
                            }
                        }
                        if (temp.size() > 0) {
                            physicaladvice.setMedicalScience(temp.stream().map(MedicalScience::getDetail).collect(Collectors.joining(",")));
                        }

                        physicaladvice.setHealthAdvice(abnormal.getCheckResult() + ":" + abnormal.getDoctorSuggest());
                    } else {
                        if (medicalSciences.stream().anyMatch(x -> x.getTitle().contains(abnormal.getAbnormalName()))) {
                            List<MedicalScience> medicalScience = medicalSciences.stream().filter(x -> x.getTitle().contains(abnormal.getAbnormalName())).collect(Collectors.toList());
                            if (medicalScience.size() > 0)
                                physicaladvice.setMedicalScience(medicalScience.stream().map(MedicalScience::getDetail).collect(Collectors.joining(",")));
                        }
                        physicaladvice.setHealthAdvice(abnormal.getAbnormalName() + ":" + abnormal.getDoctorSuggest());
                    }
                    dimePhysicaladviceMapper.insertDimePhysicaladvice(physicaladvice);
                }
            }

            //回写项目结果
            List<CheckUnit> checkUnitList = report.getData().getCheckUnitList();

            //小结
            HashMap<String, String> groupmap = new HashMap<>();


            for (CheckUnit unit : checkUnitList) {

                List<String> CombsdefaultTag = new ArrayList<>();

                for (ItemDetailGroup Group : unit.getItemDetailGroupList()) {

                    List<String> PircUrls = new ArrayList<>();


                    String groupid = "";
                    String groupname = "";


                    // 处理弃检项目
                    if (Group.getItemDetailList() == null) {

                        List<ItemDetail> itemDetailList = new ArrayList<>();

                        Combo combo = new Combo();
                        combo.setCombCode(unit.getCheckUnitCode());
                        combo.setCombName(unit.getCheckUnitName());

                        R<List<ComboBase>> comboBaseR = remoteBaseCombService.getCombs(combo, SecurityConstants.INNER);

                        if (comboBaseR.getCode() != R.FAIL) {
                            List<ComboBase> comboBaseList = comboBaseR.getData();
                            if ((long) comboBaseList.size() > 0) {
                                List<Item> items = comboBaseList.get(0).getItems();
                                if (items != null && items.size() > 0) {
                                    for (Item itemdetail : items) {

                                        ItemDetail itemDetail = new ItemDetail();
                                        itemDetail.setItemCode(unit.getCheckUnitCode());
                                        itemDetail.setItemName(unit.getCheckUnitName());
                                        itemDetail.setItemDetailCode(itemdetail.getItemCode());
                                        itemDetail.setItemDetailName(itemDetail.getItemName());
                                        itemDetail.setItemDetailResult("项目弃检");
                                        itemDetail.setComment("Lack");

                                        itemDetailList.add(itemDetail);
                                    }
                                }
                            }
                        }
                        Group.setItemDetailList(itemDetailList);
                    }


                    for (ItemDetail itemDetail : Group.getItemDetailList()) {
                        R<Combo> basecomb_R = remoteBaseCombService.getComb(itemDetail.getItemCode(), SecurityConstants.INNER);
                        if (basecomb_R.getCode() == R.FAIL) {
                            throw new ServiceException(itemDetail.getItemName() + ">为查询到基础项目信息！");
                        }

                        Combo _comb = basecomb_R.getData();

                        //未维护项目弃检
                        if (_comb == null) {
                            System.out.print(itemDetail.getItemCode() + ":" + itemDetail.getItemName() + ">>>蝶美缺少项目信息！----------------------");
                            continue;
                        }
                        //电测听 问诊 和肺功能 不取 结果   07 暂定 肺功能
                        if (Objects.equals(_comb.getCombType(), "05") || Objects.equals(_comb.getCombType(), "06") || Objects.equals(_comb.getCombType(), "07")) {
                            continue;
                        }


                        DimePhysicalitems searchitems = new DimePhysicalitems();
                        searchitems.setPhysicalRegisterId(physicalregister.getId());
                        searchitems.setItemCode(itemDetail.getItemDetailCode());

                        DimePhysicalitems physicalitems = dimePhysicalitemsMapper.getItemByPhysicalIDAndItemCode(searchitems);
                        try {

                            groupid = physicalitems.getBaseGroupId();
                            groupname = physicalitems.getGroupName();


                            itemDetail.setRange(itemDetail.getRange().replace("~", "-").replace("--", "-"));

                            if (_comb.getDefaultTag() == 1 && !CombsdefaultTag.contains(_comb.getCombCode())) {
                                CombsdefaultTag.add(_comb.getCombCode());
                            }
                            physicalitems.setResult(itemDetail.getItemDetailResult());
                            physicalitems.setUnit(itemDetail.getUnitType());
                            physicalitems.setValDefault(itemDetail.getRange());
                            physicalitems.setResultInputDate(Group.getResultTime() == null ? new Date() : DateUtils.parseDate(Group.getResultTime()));
                            physicalitems.setResultTag(itemDetail.getResultFlag() != null ? itemDetail.getResultFlag().toString() : "");
                            physicalitems.setRemark(itemDetail.getExtraUrl() != null ? itemDetail.getExtraUrl().toString() : "");

                            physicalitems.setUpdateTime(DateUtils.getNowDate());
                            physicalitems.setUpdateBy(SecurityUtils.getLoginUser().getUsername());

                            if (itemDetail.getRange() != null && itemDetail.getRange().split("-").length > 2) {
                                physicalitems.setValmin(itemDetail.getRange().split("-")[0]);
                                physicalitems.setValmax(itemDetail.getRange().split("-")[1]);

                                physicalitems.setValStandard(itemDetail.getRange());
                            }

                            if (itemDetail.getDetailDoctorList() != null && itemDetail.getDetailDoctorList().size() > 0) {
                                physicalitems.setDoctorName(itemDetail.getDetailDoctorList().get(0).getDoctorName());
                                physicalitems.setDoctortype(itemDetail.getDetailDoctorList().get(0).getSignType());
                                physicalitems.setDoctorUrl(itemDetail.getDetailDoctorList().get(0).getSignPicUrl());
                            }
                            if (itemDetail.getDetailDoctorList() != null && itemDetail.getDetailDoctorList().size() > 1) {
                                physicalitems.setRecheckdoctorName(itemDetail.getDetailDoctorList().get(1).getDoctorName());
                                physicalitems.setRecheckdoctortype(itemDetail.getDetailDoctorList().get(1).getSignType());
                                physicalitems.setRecheckdoctorUrl(itemDetail.getDetailDoctorList().get(1).getSignPicUrl());
                            }


                            //判断合格标记
                            if (itemDetail.getConclusionList() != null) {
                                List<Conclusion> sconclusions = itemDetail.getConclusionList();
                                if (sconclusions.stream().anyMatch(x -> x.getPositiveLevel().equals(1L))) {
                                    physicalitems.setPassTag(0L);
                                } else {
                                    physicalitems.setPassTag(1L);
                                }
                            }

                            if (Objects.equals(itemDetail.getComment(), "Lack")) {
                                physicalitems.setLack("1");
                                physicalitems.setPassTag(0L);
                            }


                            dimePhysicalitemsMapper.updateDimePhysicalitems(physicalitems);

                            //处理图片
                            if (itemDetail.getExtraUrl() != null && !Objects.equals(groupid, "")) {

                                List<String> Urls = Arrays.stream(itemDetail.getExtraUrl().toString().split(";")).collect(Collectors.toList());

                                for (String url : Urls) {

                                    if (!PircUrls.contains(url)) {
                                        PircUrls.add(url);
                                    }
                                }
                            }
                            //处理小组结论
                            if (!Objects.equals(groupid, "") && !groupmap.containsKey(groupid)) {
                                String groupSummary = "";

                                if (Group.getGroupSummaryList() != null && Group.getSummaryList().size() > 0) {
                                    groupSummary = String.join(",", Group.getSummaryList());
                                }
                                groupmap.put(groupid, groupSummary);
                            }
                        } catch (Exception ex) {

                            if (physicalitems != null) {
                                throw new ServiceException(physicalitems.getItemName() + ex.getMessage());
                            }
                        }
                    }

                    //处理


                    if (PircUrls.size() > 0 && !Objects.equals(groupid, "")) {

                        dimePhysicalpictureMapper.deleteDimePhysicalpictureByPhysicalIdAndGroupId(physicalregister.getId(), groupid);

                        for (String url : PircUrls) {
                            if (!SaveCombPic(url, groupid, groupname, physicalregister.getId())) {

                                throw new ServiceException(groupname + "图片保存失败！");
                            }
                        }

                    }


                }


                //处理缺省项目
                if (CombsdefaultTag.size() > 0) {
                    for (String combcode : CombsdefaultTag) {
                        DimePhysicalitems searchitems=new DimePhysicalitems();

                        searchitems.setPhysicalRegisterId(physicalregister.getId());
                        searchitems.setCombCode(combcode);

                        List<DimePhysicalitems> dimePhysicalitemsList = dimePhysicalitemsMapper.selectDimePhysicalitemsList(searchitems).stream().filter(x ->x.getResult()==null || Objects.equals(x.getResult(), "")).collect(Collectors.toList());
                        if (dimePhysicalitemsList.size() > 0) {
                            for (DimePhysicalitems dimePhysicalitems : dimePhysicalitemsList) {
                                dimePhysicalitems.setResult(".");
                                dimePhysicalitems.setPassTag(1L);
                                dimePhysicalitems.setUpdateTime(DateUtils.getNowDate());
                                dimePhysicalitems.setUpdateBy(SecurityUtils.getLoginUser().getUsername());

                                dimePhysicalitemsMapper.updateDimePhysicalitems(dimePhysicalitems);
                            }
                        }
                    }
                }
            }

            if (groupmap.size() > 0) {
                dimePhysicalconsionMapper.deleteDimePhysicalconsionByPhysicalId(physicalregister.getId());
            }

            //处理groupmap 回写流程表和 小结信息
            for (Map.Entry<String, String> entry : groupmap.entrySet()) {

                DimePhysicalitems searchitems = new DimePhysicalitems();
                searchitems.setPhysicalRegisterId(physicalregister.getId());
                searchitems.setBaseGroupId(entry.getKey());

                List<DimePhysicalitems> physicalitemsList = dimePhysicalitemsMapper.selectDimePhysicalitemsList(searchitems);

                if (physicalitemsList != null && physicalitemsList.size() > 0 && physicalitemsList.stream().noneMatch(x -> x.getResult() == null || x.getResult().equals(""))) {

                    DimePhysicalflow searchflow = new DimePhysicalflow();
                    searchflow.setPhysicalRegisterId(physicalregister.getId());
                    searchflow.setBaseGroupId(entry.getKey());

                    //流程
                    DimePhysicalflow dimePhysicalflow = dimePhysicalflowMapper.selectDimePhysicalflowList(searchflow).stream().findFirst().orElse(null);

                    if (dimePhysicalflow != null) {
                        dimePhysicalflow.setFlowStatus(1L);
                        dimePhysicalflow.setFlowInputDate(new Date());
                        dimePhysicalflow.setUpdateTime(DateUtils.getNowDate());
                        dimePhysicalflow.setUpdateBy(SecurityUtils.getLoginUser().getUsername());

                        dimePhysicalflowMapper.updateDimePhysicalflow(dimePhysicalflow);
                    }

                    //小组结论
                    DimePhysicalconsion physicalconsion = new DimePhysicalconsion();

                    physicalconsion.setId(IdUtils.fastUUID());
                    physicalconsion.setCreateTime(DateUtils.getNowDate());
                    physicalconsion.setCreateBy(SecurityUtils.getLoginUser().getUsername());
                    physicalconsion.setDimeBasegroupid(entry.getKey());
                    physicalconsion.setPhysicalRegisterId(physicalregister.getId());
                    if (physicalitemsList.stream().anyMatch(x -> x.getPassTag().equals(0L))) {
                        physicalconsion.setPassTag("0");
                    } else {
                        physicalconsion.setPassTag("1");
                    }

                    if (entry.getValue().equals("")) {
                        if (physicalitemsList.stream().anyMatch(x -> x.getPassTag().equals(0L))) {
                            List<DimePhysicalitems> abnormalitems = physicalitemsList.stream().filter(x -> x.getPassTag().equals(0L)).collect(Collectors.toList());
                            if (abnormalitems.size() > 0) {
                                physicalconsion.setConclusion(abnormalitems.stream().map(x -> x.getItemName() + ":" + x.getResult() + x.getUnit()).collect(Collectors.joining(";")));
                            }
                        } else {

                            physicalconsion.setConclusion("未见明显异常！");
                        }
                    } else {
                        physicalconsion.setConclusion(entry.getValue());
                    }


                    dimePhysicalconsionMapper.insertDimePhysicalconsion(physicalconsion);
                }
            }

            UpdatePhysicalRegistercompletStatus(physicalregister);
            return 1;

        } else {
            throw new ServiceException(report.getErrorMsg() != null ? report.getErrorMsg().toString() : "获取报告失败！");
        }
    }


    @Override
    public List<InquiryPhysicalregister> getTodayRegisterinquirylist(SearchPhysicalregister dimePhysicalregister) {

        return dimePhysicalregisterMapper.selectRegisterinquirylist(dimePhysicalregister);
    }



    @Override
    public List<DimePhysicalregister> searchDimePhysicalregisterList(SearchPhysicalregister searchPhysicalregister) {

        return dimePhysicalregisterMapper.selectDimePhysicalregisterList(searchPhysicalregister);
    }

    @Override
    public List<DimePhysicalregister> searchMainCheckDimePhysicalregisterList(SearchPhysicalregister searchPhysicalregister) {

        return dimePhysicalregisterMapper.selectRegistermainchecklist(searchPhysicalregister);
    }

    @Override
    public List<DimePhysicalregister> selectInputRegistersByGroupId(String groupId) {
        return dimePhysicalregisterMapper.selectPhysicalRegistersByGroupId(groupId);
    }

    @Override
    public DimePhysicalregister selectInputRegisterBycheckCode(String checkCode) {
        DimePhysicalregister dimePhysicalregister = dimePhysicalregisterMapper.selectDimePhysicalregisterByVid(checkCode);
        if (dimePhysicalregister != null) {
            List<DimePhysicalflow> dimePhysicalflows = dimePhysiacaflowService.getDimePhysiacaflowListByUserId(SecurityUtils.getUserId().toString());
            dimePhysicalflowMapper.selectDimePhysiacaflowByPhysicalId(dimePhysicalregister.getId());
            if (dimePhysicalflows.stream().anyMatch(x -> Objects.equals(x.getPhysicalRegisterId(), dimePhysicalregister.getId()))) {
                return dimePhysicalregister;
            }
        }
        return null;
    }


    //更新主表完成标记
    public boolean UpdatePhysicalRegistercompletStatus(DimePhysicalregister _dimePhysicalregister) {

        if (_dimePhysicalregister.getCheckDate() == null) {
            _dimePhysicalregister.setCheckDate(new Date());
        }

        if (Long.parseLong(_dimePhysicalregister.getCompletStatus()) > 1) {
            return false;
        }

        DimePhysicalflow searchflow = new DimePhysicalflow();
        searchflow.setPhysicalRegisterId(_dimePhysicalregister.getId());

        List<DimePhysicalflow> dimePhysicalflows = dimePhysiacaflowService.selectDimePhysicalflowList(searchflow);
        if (dimePhysicalflows != null && dimePhysicalflows.size() > 0) {
            if (dimePhysicalflows.stream().map(DimePhysicalflow::getFlowStatus).anyMatch(x -> x == 0L)) {
                _dimePhysicalregister.setCompletStatus("0");
            } else {
                _dimePhysicalregister.setCompletStatus("1");
            }

        }
        dimePhysicalregisterMapper.updateDimePhysicalregister(_dimePhysicalregister);


        return true;
    }


    @Override
    public RegisterViewDto getPhysicalInfo(DimePhysicalregister dimePhysicalregister) {

        RegisterViewDto registerViewDto = MappingRegister(dimePhysicalregister);

        List<DimePhysicalflow> dimePhysicalflowList = dimePhysicalflowMapper.selectDimePhysiacaflowByPhysicalId(registerViewDto.getId());

        List<RegisterflowViewDto> registerflowViewDtoList = new ArrayList<>();

        if (dimePhysicalflowList != null && dimePhysicalflowList.size() > 0) {
            for (DimePhysicalflow dimePhysicalflow : dimePhysicalflowList) {

                RegisterflowViewDto registerflowViewDto = MappingRegisterflow(dimePhysicalflow);

                List<DimePhysicalitems> dimePhysicalitemsList = dimePhysicalitemsMapper.selectPhysicalitemsByphysicalIdAndGroupid(registerViewDto.getId(), dimePhysicalflow.getBaseGroupId());
                registerflowViewDto.setDimePhysicalitemsList(dimePhysicalitemsList);

                DimePhysicalconsion dimePhysicalconsion = dimePhysicalconsionMapper.selectDimePhysicalconsionByPhysicalIdAndGroupId(registerViewDto.getId(), dimePhysicalflow.getBaseGroupId());
                if (dimePhysicalconsion != null)
                    registerflowViewDto.setDimePhysicalconsion(dimePhysicalconsion);

                registerflowViewDtoList.add(registerflowViewDto);
            }

        }
        registerViewDto.setRegisterflowViewDtoList(registerflowViewDtoList);

        return registerViewDto;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDimePhysical(PhysicalDto dimePhysicalregister) {
        int rows = 0;

        rows += dimePhysicalregisterMapper.updateDimePhysicalregister(dimePhysicalregister);

        if (dimePhysicalregister.dimeBaseharmList != null && dimePhysicalregister.dimeBaseharmList.size() > 0) {
            List<DimePhysicalharms> dimePhysicalharms = dimePhysicalharmsMapper.selectDimePhysicalharmsByPhysicalId(dimePhysicalregister.getId());
            if (dimePhysicalharms != null && dimePhysicalharms.size() > 0) {
                dimePhysicalharmsMapper.deleteDimePhysicalharmsByPhysicalId(dimePhysicalregister.getId());
            }

            for (DimeBaseharm dimeBaseharm : dimePhysicalregister.dimeBaseharmList) {

                DimePhysicalharms dimePhysicalharm = new DimePhysicalharms();
                dimePhysicalharm.setCreateTime(DateUtils.getNowDate());
                dimePhysicalharm.setId(IdUtils.fastUUID());
                dimePhysicalharm.setCreateBy(SecurityUtils.getUsername());
                dimePhysicalharm.setPhysicalRegisterId(dimePhysicalregister.getId());
                dimePhysicalharm.setBaseHarmId(dimeBaseharm.getId());
                dimePhysicalharm.setBaseHarmName(dimeBaseharm.getHamName());
                dimePhysicalharm.setBaseHarmcode(dimeBaseharm.getHamrCode());
                rows += dimePhysicalharmsMapper.insertDimePhysicalharms(dimePhysicalharm);

            }


        }
        return rows;
    }

    @Override
    public PhysicalDto selectDimePhysicalById(String id) {

        DimePhysicalregister dimePhysicalregister=dimePhysicalregisterMapper.selectDimePhysicalregisterById(id);

        if(dimePhysicalregister!=null)
        {
            PhysicalDto dto = MappingPhysicalRegister(dimePhysicalregister);

            List<DimePhysicalharms>dimePhysicalharms=dimePhysicalharmsMapper.selectDimePhysicalharmsByPhysicalId(dimePhysicalregister.getId());

            List<DimeBaseharm>dimeBaseharms=new ArrayList<>();
            if(dimePhysicalharms!=null&&dimePhysicalharms.size()>0)
            {
                for (DimePhysicalharms dimePhysicalharms1 : dimePhysicalharms) {
                    DimeBaseharm dimeBaseharm = new DimeBaseharm();
                    dimeBaseharm.setId(dimePhysicalharms1.getBaseHarmId());
                    dimeBaseharm.setHamName(dimePhysicalharms1.getBaseHarmName());
                    dimeBaseharms.add(dimeBaseharm);
                }
            }
            dto.dimeBaseharmList=dimeBaseharms;

            return dto;
        }


        return null;
    }

    @Override
    public List<InquiryPhysicalregister> selectDimePhysicalregisterinquiryList(SearchPhysicalregister searchPhysicalregister) {

        return dimePhysicalregisterMapper.selectRegisterinquirylist(searchPhysicalregister);
    }

    private PhysicalDto MappingPhysicalRegister(DimePhysicalregister dimePhysicalregister) {
        PhysicalDto physicalDto = new PhysicalDto();
        physicalDto.setHeadUrl(dimePhysicalregister.getHeadUrl());
        physicalDto.setHeadpicture(dimePhysicalregister.getHeadpicture());
        physicalDto.setNation(dimePhysicalregister.getNation());
        physicalDto.setId(dimePhysicalregister.getId());
        physicalDto.setCheckCode(dimePhysicalregister.getCheckCode());
        physicalDto.setIdNo(dimePhysicalregister.getIdNo());
        physicalDto.setName(dimePhysicalregister.getName());
        physicalDto.setPersonType(dimePhysicalregister.getPersonType());
        physicalDto.setCheckType(dimePhysicalregister.getCheckType());
        physicalDto.setIdNoType(dimePhysicalregister.getIdNoType());
        physicalDto.setSex(dimePhysicalregister.getSex());
        physicalDto.setAge(dimePhysicalregister.getAge());
        physicalDto.setMarriage(dimePhysicalregister.getMarriage());
        physicalDto.setPhone(dimePhysicalregister.getPhone());
        physicalDto.setAddress(dimePhysicalregister.getAddress());
        physicalDto.setBirthday(dimePhysicalregister.getBirthday());
        physicalDto.setBasePackageId(dimePhysicalregister.getBasePackageId());
        physicalDto.setPackageName(dimePhysicalregister.getPackageName());
        physicalDto.setBaseCompanyId(dimePhysicalregister.getBaseCompanyId());
        physicalDto.setCompanyName(dimePhysicalregister.getCompanyName());
        physicalDto.setRegisterDate(dimePhysicalregister.getRegisterDate());
        physicalDto.setCheckDate(dimePhysicalregister.getCheckDate());
        physicalDto.setChannel(dimePhysicalregister.getChannel());
        physicalDto.setReportPrintDate(dimePhysicalregister.getReportPrintDate());
        physicalDto.setMainCheckDate(dimePhysicalregister.getMainCheckDate());
        physicalDto.setReportPrinter(dimePhysicalregister.getReportPrinter());
        physicalDto.setJobType(dimePhysicalregister.getJobType());
        physicalDto.setEmpNo(dimePhysicalregister.getEmpNo());
        physicalDto.setDept(dimePhysicalregister.getDept());
        physicalDto.setWorkStatus(dimePhysicalregister.getWorkStatus());
        physicalDto.setCompletStatus(dimePhysicalregister.getCompletStatus());
        physicalDto.setHarmfacter(dimePhysicalregister.getHarmfacter());
        physicalDto.setPassword(dimePhysicalregister.getPassword());
        physicalDto.setWorkYears(dimePhysicalregister.getWorkYears());
        physicalDto.setWorkMonths(dimePhysicalregister.getWorkMonths());
        physicalDto.setTouchYears(dimePhysicalregister.getTouchYears());
        physicalDto.setTouchMonths(dimePhysicalregister.getTouchMonths());
        physicalDto.setNeedAsk(dimePhysicalregister.getNeedAsk());
        physicalDto.setReCheckTag(dimePhysicalregister.getReCheckTag());
        physicalDto.setLastCheckCode(dimePhysicalregister.getLastCheckCode());
        physicalDto.setCombLack(dimePhysicalregister.getCombLack());
        physicalDto.setSocialCode(dimePhysicalregister.getSocialCode());
        physicalDto.setServiceUid(dimePhysicalregister.getServiceUid());
        physicalDto.setSoaOrderNo(dimePhysicalregister.getSoaOrderNo());
        physicalDto.setPlatformTag(dimePhysicalregister.getPlatformTag());
        physicalDto.setCheckResult(dimePhysicalregister.getCheckResult());
        physicalDto.setMainConclusion(dimePhysicalregister.getMainConclusion());
        physicalDto.setHealthSuggestion(dimePhysicalregister.getHealthSuggestion());
        physicalDto.setMainCheckDoctor(dimePhysicalregister.getMainCheckDoctor());
        physicalDto.setTakeReportType(dimePhysicalregister.getTakeReportType());
        physicalDto.setIsValid(dimePhysicalregister.getIsValid());
        physicalDto.setShopCode(dimePhysicalregister.getShopCode());
        physicalDto.setTouchHarms(dimePhysicalregister.getTouchHarms());
        physicalDto.setNationality(dimePhysicalregister.getNationality());
        physicalDto.setRegistertype(dimePhysicalregister.getRegistertype());
        physicalDto.setSearchValue(dimePhysicalregister.getSearchValue());
        physicalDto.setCreateBy(dimePhysicalregister.getCreateBy());
        physicalDto.setCreateTime(dimePhysicalregister.getCreateTime());
        physicalDto.setUpdateBy(dimePhysicalregister.getUpdateBy());
        physicalDto.setUpdateTime(dimePhysicalregister.getUpdateTime());
        physicalDto.setRemark(dimePhysicalregister.getRemark());
        physicalDto.setParams(dimePhysicalregister.getParams());
        return physicalDto;

    }


    private RegisterViewDto MappingRegister(DimePhysicalregister dimePhysicalregister) {
        RegisterViewDto registerViewDto = new RegisterViewDto();
        registerViewDto.setHeadUrl(dimePhysicalregister.getHeadUrl());
        registerViewDto.setId(dimePhysicalregister.getId());
        registerViewDto.setCheckCode(dimePhysicalregister.getCheckCode());
        registerViewDto.setIdNo(dimePhysicalregister.getIdNo());
        registerViewDto.setName(dimePhysicalregister.getName());
        registerViewDto.setPersonType(dimePhysicalregister.getPersonType());
        registerViewDto.setCheckType(dimePhysicalregister.getCheckType());
        registerViewDto.setIdNoType(dimePhysicalregister.getIdNoType());
        registerViewDto.setSex(dimePhysicalregister.getSex());
        registerViewDto.setAge(dimePhysicalregister.getAge());
        registerViewDto.setMarriage(dimePhysicalregister.getMarriage());
        registerViewDto.setPhone(dimePhysicalregister.getPhone());
        registerViewDto.setAddress(dimePhysicalregister.getAddress());
        registerViewDto.setBirthday(dimePhysicalregister.getBirthday());
        registerViewDto.setBasePackageId(dimePhysicalregister.getBasePackageId());
        registerViewDto.setPackageName(dimePhysicalregister.getPackageName());
        registerViewDto.setBaseCompanyId(dimePhysicalregister.getBaseCompanyId());
        registerViewDto.setCompanyName(dimePhysicalregister.getCompanyName());
        registerViewDto.setRegisterDate(dimePhysicalregister.getRegisterDate());
        registerViewDto.setCheckDate(dimePhysicalregister.getCheckDate());
        registerViewDto.setChannel(dimePhysicalregister.getChannel());
        registerViewDto.setReportPrintDate(dimePhysicalregister.getReportPrintDate());
        registerViewDto.setMainCheckDate(dimePhysicalregister.getMainCheckDate());
        registerViewDto.setReportPrinter(dimePhysicalregister.getReportPrinter());
        registerViewDto.setJobType(dimePhysicalregister.getJobType());
        registerViewDto.setEmpNo(dimePhysicalregister.getEmpNo());
        registerViewDto.setDept(dimePhysicalregister.getDept());
        registerViewDto.setWorkStatus(dimePhysicalregister.getWorkStatus());
        registerViewDto.setCompletStatus(dimePhysicalregister.getCompletStatus());
        registerViewDto.setHarmfacter(dimePhysicalregister.getHarmfacter());
        registerViewDto.setPassword(dimePhysicalregister.getPassword());
        registerViewDto.setWorkYears(dimePhysicalregister.getWorkYears());
        registerViewDto.setWorkMonths(dimePhysicalregister.getWorkMonths());
        registerViewDto.setTouchYears(dimePhysicalregister.getTouchYears());
        registerViewDto.setTouchMonths(dimePhysicalregister.getTouchMonths());
        registerViewDto.setNeedAsk(dimePhysicalregister.getNeedAsk());
        registerViewDto.setReCheckTag(dimePhysicalregister.getReCheckTag());
        registerViewDto.setLastCheckCode(dimePhysicalregister.getLastCheckCode());
        registerViewDto.setCombLack(dimePhysicalregister.getCombLack());
        registerViewDto.setSocialCode(dimePhysicalregister.getSocialCode());
        registerViewDto.setServiceUid(dimePhysicalregister.getServiceUid());
        registerViewDto.setSoaOrderNo(dimePhysicalregister.getSoaOrderNo());
        registerViewDto.setPlatformTag(dimePhysicalregister.getPlatformTag());
        registerViewDto.setCheckResult(dimePhysicalregister.getCheckResult());
        registerViewDto.setMainConclusion(dimePhysicalregister.getMainConclusion());
        registerViewDto.setHealthSuggestion(dimePhysicalregister.getHealthSuggestion());
        registerViewDto.setMainCheckDoctor(dimePhysicalregister.getMainCheckDoctor());
        registerViewDto.setTakeReportType(dimePhysicalregister.getTakeReportType());
        registerViewDto.setIsValid(dimePhysicalregister.getIsValid());
        registerViewDto.setShopCode(dimePhysicalregister.getShopCode());
        registerViewDto.setTouchHarms(dimePhysicalregister.getTouchHarms());
        registerViewDto.setNationality(dimePhysicalregister.getNationality());
        registerViewDto.setSearchValue(dimePhysicalregister.getSearchValue());
        registerViewDto.setCreateBy(dimePhysicalregister.getCreateBy());
        registerViewDto.setCreateTime(dimePhysicalregister.getCreateTime());
        registerViewDto.setUpdateBy(dimePhysicalregister.getUpdateBy());
        registerViewDto.setUpdateTime(dimePhysicalregister.getUpdateTime());
        registerViewDto.setRemark(dimePhysicalregister.getRemark());
        registerViewDto.setParams(dimePhysicalregister.getParams());
        return registerViewDto;

    }

    private RegisterflowViewDto MappingRegisterflow(DimePhysicalflow dimePhysicalflow) {
        RegisterflowViewDto registerflowViewDto = new RegisterflowViewDto();
        registerflowViewDto.setGroupName(dimePhysicalflow.getGroupName());
        registerflowViewDto.setId(dimePhysicalflow.getId());
        registerflowViewDto.setPhysicalRegisterId(dimePhysicalflow.getPhysicalRegisterId());
        registerflowViewDto.setBaseGroupId(dimePhysicalflow.getBaseGroupId());
        registerflowViewDto.setType(dimePhysicalflow.getType());
        registerflowViewDto.setGroupName(dimePhysicalflow.getGroupName());
        registerflowViewDto.setFlowStatus(dimePhysicalflow.getFlowStatus());
        registerflowViewDto.setFlowInputDate(dimePhysicalflow.getFlowInputDate());
        registerflowViewDto.setCreateBy(dimePhysicalflow.getCreateBy());
        registerflowViewDto.setCreateTime(dimePhysicalflow.getCreateTime());
        registerflowViewDto.setUpdateBy(dimePhysicalflow.getUpdateBy());
        registerflowViewDto.setUpdateTime(dimePhysicalflow.getUpdateTime());
        registerflowViewDto.setRemark(dimePhysicalflow.getRemark());
        registerflowViewDto.setParams(dimePhysicalflow.getParams());
        return registerflowViewDto;

    }

    ////http://mn-bianque.oss-cn-shanghai.aliyuncs.com/60139534162756/NewFile_6646030832286529.jpeg?Expires=1698394131&OSSAccessKeyId=LTAI4GFy4JzuxQN3J3BkCuTT&Signature=rExlc3BMGF6keXnOgXeS2s2lMzw%3D
    private boolean SaveCombPic(String Url, String groupId, String groupname, String PhysicalId)
    {

        String  splitfileName= Url.substring(Url.lastIndexOf("/") + 1);

        String filename="";
        if(splitfileName.contains("?"))
        {
            filename = splitfileName.substring(0, splitfileName.indexOf("?"));
        }
        else
        {
            filename=splitfileName;
        }

        byte[] bytes = ImageUtils.readFile(Url);
        InputStream inputStream = null;
        if (bytes != null) {
            inputStream = new ByteArrayInputStream(bytes);
            try {
                MultipartFile file = new MyMultipartFile(filename, filename, String.valueOf(ContentType.IMAGE_JPEG), inputStream);

                R<SysFile> sysFileR = remoteFileService.upload(file);
                if(sysFileR.getCode()!=R.FAIL)
                {
                    DimePhysicalpicture dimePhysicalpicture = new DimePhysicalpicture();
                    dimePhysicalpicture.setId(IdUtils.fastUUID());
                    dimePhysicalpicture.setCreateTime(DateUtils.getNowDate());
                    dimePhysicalpicture.setCreateBy(SecurityUtils.getLoginUser().getUsername());
                    dimePhysicalpicture.setDimeBasegroupid(groupId);
                    dimePhysicalpicture.setGroupName(groupname);
                    dimePhysicalpicture.setPhysicalRegisterId(PhysicalId);
                    dimePhysicalpicture.setFilesuffix(String.valueOf(ContentType.IMAGE_JPEG));
                    dimePhysicalpicture.setPicturtetype("1");
                    dimePhysicalpicture.setFilepath(sysFileR.getData().getUrl());
                    dimePhysicalpicture.setFilename(filename);
                    dimePhysicalpictureMapper.insertDimePhysicalpicture(dimePhysicalpicture);
                }

            } catch (IOException e) {
                throw new ServiceException(e.getMessage());
            }
        }


        return true;
    }


}

